package com.jie.service.impl;

import com.jie.constant.CommonConst;
import com.jie.dto.UserDetailDTO;
import com.jie.login.UserDetailsServiceImpl;
import com.jie.mapper.UserInfoMapper;
import com.jie.mapper.UserRoleMapper;
import com.jie.pojo.UserAdmin;
import com.jie.mapper.UserAdminMapper;
import com.jie.pojo.UserInfo;
import com.jie.pojo.UserRole;
import com.jie.service.UserAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.util.JwtTokenUtil;
import com.jie.vo.CommonResponse;
import com.jie.vo.UserLoginProcessVo;
import com.jie.vo.UserRegisteredVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;

import static com.jie.constant.CommonConst.IMAGES;
import static com.jie.constant.UserConstant.USER_INFO;
import static com.jie.enums.ZoneEnum.SHANGHAI;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaojie
 * @since 2023-11-01
 */
@Slf4j
@Service
public class UserAdminServiceImpl extends ServiceImpl<UserAdminMapper, UserAdmin> implements UserAdminService {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserInfoMapper userInfoDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserRoleMapper userRoleDao;
    /**
     * 登录接口
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param request
     * @return
     */
    @Override
    public CommonResponse login(String username, String password, String code, HttpServletRequest request) {
        //验证码
//        String captcha = (String) request.getSession().getAttribute("captcha");
//        if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(code)) {
//            return CommonResponse.buildError("验证码错误,重新输入");
//        }
        //这个东西其实就相当于我们的根据用户名获取用户信息，因为admin实现类UserDetails接口
        UserDetailDTO userDetails = (UserDetailDTO)userDetailsService.loadUserByUsername(username);
        //这里要考虑我们前端传过来的是明文密码，我们这里判断的是加密的所有要这样判断
        //使用springsecurity提供的加密工具
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return CommonResponse.buildError("用户名或密码不正确!");
        }
        if (!userDetails.isEnabled()) {
            return CommonResponse.buildError("账号被禁用，请联系管理员!");
        }
        //返回token
        return token(userDetails);
    }
    //注册后可以直接返回token进入系统
    public CommonResponse login(String username, String password, HttpServletRequest request) {
        //这个东西其实就相当于我们的根据用户名获取用户信息，因为admin实现类UserDetails接口
        UserDetailDTO userDetails = (UserDetailDTO)userDetailsService.loadUserByUsername(username);
        //返回token
        return token(userDetails);
    }
    /**
     * 返回token
     * @param userDetails
     * @return
     */
    public CommonResponse token(UserDetailDTO userDetails){
        //更新security登录对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //将用户信息往redis存储一份
        if (!redisTemplate.hasKey(USER_INFO+":"+userDetails.getUsername())) {
            redisTemplate.opsForValue().set(USER_INFO+":"+userDetails.getUsername(),UserLoginProcessVo.builder().
                    userInfoId(userDetails.getUserInfoId()).terminal(userDetails.getTerminal()).build());
        }
        //成功之后分配令牌
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResponse.buildSuccess(tokenMap);
    }

    /**
     * 注册
     * @param userRegisteredVO
     * @return
     */
    @Transactional
    @Override
    public CommonResponse registeredUserAuth(UserRegisteredVO userRegisteredVO, HttpServletRequest request) {
        //TODO 判断redis有无用户
        if (redisTemplate.opsForHash().hasKey(CommonConst.USER_REGISTERED,userRegisteredVO.getEmail())){
            return CommonResponse.buildError("账户早已注册,请转移登录页面");
        }
//        没有就存入用户信息
        redisTemplate.opsForHash().put(CommonConst.USER_REGISTERED,userRegisteredVO.getEmail(),userRegisteredVO.getNickname());
//        先注册用户信息表 默认头像地址
        UserInfo userInfo = UserInfo.builder().nickname(userRegisteredVO.getNickname())
                .avatar(IMAGES).isDisable(0).email(userRegisteredVO.getEmail()).createTime(LocalDateTime.now(ZoneId.of(SHANGHAI.getZone()))).build();
        //注册到用户信息表中
        userInfoDao.addUserInfo(userInfo);
        //注册用户表 phone做username唯一
        UserAdmin user = UserAdmin.builder().userInfoId(userInfo.getId()).username(userRegisteredVO.getEmail())
                .password(passwordEncoder.encode(userRegisteredVO.getPassword()))
                .createTime(LocalDateTime.now(ZoneId.of(SHANGHAI.getZone()))).build();
        this.baseMapper.insert(user);
        userRoleDao.insert(UserRole.builder().userId(user.getId()).roleId(2).build());
        return login(userRegisteredVO.getEmail(), userRegisteredVO.getPassword(),request);
    }

}
